package com.zzw.paymentdemo.controller;

import com.zzw.paymentdemo.entity.OrderInfo;
import com.zzw.paymentdemo.enums.OrderStatus;
import com.zzw.paymentdemo.service.OrderInfoService;
import com.zzw.paymentdemo.service.WxPayService;
import com.zzw.paymentdemo.vo.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

/**
 * @author zzw
 * @date 2023/5/12 17:35
 */
@Slf4j
@CrossOrigin //支持跨域
@RestController
@RequestMapping("/api/order-info")
@Api(tags = "商品管理订单")
public class OrderInfoController {


    @Autowired
    OrderInfoService orderInfoService;

    @Autowired
    WxPayService wxPayService;
    /**
     * 按时间倒序显示订单列表
     * @author zzw
     * @date 2023/5/12 17:37
     * @return com.zzw.paymentdemo.entity.OrderInfo
     */
    @ApiOperation("订单列表")
    @GetMapping("/list")
    public R list(){
        List<OrderInfo> list= orderInfoService.listOrderByCreateTimeDesc();
        return R.ok().data("list",list);
    }

    /**
     * 查询本地订单状态
     * 前端相继设置定时器判断返回状态，
     * 若为0则支付成功，清除定时器并跳转相应页面；
     * 若为101则支付中，继续定时调用该接口进行状态判断
     */
    @ApiOperation("查询本地订单状态")
    @GetMapping("/query-order-status/{orderNo}")
    public R queryOrderStatus(@PathVariable String orderNo) {
        String orderStatus = orderInfoService.getOrderStatus(orderNo);
        if (OrderStatus.SUCCESS.getType().equals(orderStatus)) {//支付成功
            return R.ok();
        }
        return R.ok().setCode(101).setMessage("支付中...");
    }

    /**
     *用户取消订单
     * @param orderNo
     * @return com.zzw.paymentdemo.vo.R
     **/
    @ApiOperation("用户取消订单")
    @PostMapping("/cancel/{orderNo}")
    public R cancel(@PathVariable String orderNo) throws IOException {
        log.info("取消订单");

        wxPayService.cancelOrder(orderNo);
        return R.ok().setMessage("用户订单已取消");
    }


}
